<?php
namespace Api\Controller;
use Think\Controller;
class TakeOutController extends CommonController {
    //获取轮播图列表
    public function getAdList(){
        $map = array();
        $map['wid'] = session('wid');
        $map['status'] = 1;
        $result = M('takeout_ad')
            ->where($map)
            ->select();

        return $this->ajaxReturn($result);
    }
    //获取店铺类型列表
    public function getShopTypeList(){
        $map = array();
        $map['wid'] = session('wid');
        $map['status'] = 1;
        $result = M('takeout_shoptype')
            ->where($map)
            ->select();
        return $this->ajaxReturn($result);
    }
    //获取店铺列表
    public function getStoreList(){
        $wid = session('wid');
        $lat = $_POST['lat'];
        $lng = $_POST['lng'];
        $where=" WHERE wid=".$wid." and is_open=1";
        $pageindex = max(1,intval($_POST['page']));
        $pagesize = $_POST['pagesize'];
        $sql="SELECT *, ROUND(6378.138*2*ASIN(SQRT(POW(SIN(($lat*PI()/180-SUBSTRING_INDEX(coordinates, ',', 1)*PI()/180)/2),2)+COS($lat*PI()/180)*COS(SUBSTRING_INDEX(coordinates, ',', 1)*PI()/180)*POW(SIN(($lng*PI()/180-SUBSTRING_INDEX(coordinates, ',', -1)*PI()/180)/2),2)))*1000) AS juli  
     FROM tp_takeout_store".$where ." ORDER BY juli ASC";
        $select_sql =$sql." LIMIT " .($pageindex - 1) * $pagesize.",".$pagesize;
        $result = M()->query($select_sql);
        $this->ajaxReturn($result);
    }
    //获取店铺信息
    public function getStoreInfo(){
        $member = M('member')
            ->where(array('openid'=>$_POST['openid']))
            ->getField('mid');
        if($member['mid']){
            $data = array();
            $data['user_id']=$member['mid'];
            $data['store_id']=$_POST['id'];
            $data['time']=date("Y-m-d");
            $list = M('takeout_traffic')
                ->where($data)
                ->find();
            if(!$list){
              M('takeout_traffic')
                  ->add($data);
            }
        }
          

        // $res=pdo_get('wpdc_store',array('uniacid'=>$_W['uniacid'],'id'=>$_POST['id']));
        $map = array();
        $map['wid'] = session('wid');
        $map['id'] = $_POST['id'];
        $res = M('takeout_store')
            ->where($map)
            ->find();
        if($res['img']){
            if(strlen($res['img'])>51){
              $res['img']= explode(',',$res['img']);
            }else{
              $res['img']=array(
                0=>$res['img']
                );
            }  
        }
        if($res['yyzz']){
           if(strlen($res['yyzz'])>51){
            $res['yyzz']= explode(',',$res['yyzz']);
          }else{
            $res['yyzz']=array(
              0=>$res['yyzz']
              );
          }
        }
        if($res['environment']){
            if(strlen($res['environment'])>51){
              $res['environment']= explode(',',$res['environment']);
            }else{
              $res['environment']=array(
                0=>$res['environment']
                );
            }
        }
        $res['store_video'] = $this->video($res['store_video']);

        /*$lmap['d.wid'] = session('wid');
        $lmap['d.store_id'] = I('id');
        $lmap['dishes_type'] = 3;
        //获取菜品列表
        $list = M('takeout_dishes')->alias('d')
            ->field('d.*,t.type_name')
            ->join('tp_takeout_type t on t.id = d.type_id')
            ->where($lmap)
            ->order("sorting desc")
            ->limit(3)
            ->select();*/
        $lmap['s.openid'] = $_POST['openid'];
        $lmap['s.wid'] = session('wid');
        $list = M('goods')->alias('g')
            ->field('g.*')
            ->join('tp_shop s on s.shop_id = g.shop_id')
            ->where($lmap)
            ->limit(3)
            ->select();
        //根据openid查shop表
        $shop = M('shop')->where(['wid'=>session('wid'),'openid'=>$_POST['openid']])->find();
        if($shop['pics']){
            if(strpos(",",$shop['pics'])){
            $shop['pics']= explode(',',$shop['pics']);
            }else{
                $shop['pics']=array(
                    0=>$shop['pics']
                );
            }
        }
        $res['goods'] = $list;
        $res['shop'] = $shop;
        $this->ajaxReturn($res);
    }
    function video($video){
        $vid=trim(strrchr($video, '/'),'/');
        $vid=substr($vid,0,-5);
        $json=file_get_contents("http://vv.video.qq.com/getinfo?vids=".$vid."&platform=101001&charge=0&otype=json");
       // echo $json;die;
        $json=substr($json,13);
        $json=substr($json,0,-1);
        $a=json_decode(html_entity_decode($json));
        $sz=json_decode(json_encode($a),true);
       // print_R($sz);die;
        $url=$sz['vl']['vi']['0']['ul']['ui']['3']['url'];
        $fn=$sz['vl']['vi']['0']['fn'];
        $fvkey=$sz['vl']['vi']['0']['fvkey'];
        $url=$url.$fn.'?vkey='.$fvkey;
        return  $url;
    }
    //获取商家减满列表
    public function getReductionList(){
        $result = M('takeout_reduction')
            ->where(array('store_id'=>$_POST['id']))
            ->select();
        $this->ajaxReturn($result);
    }

    //商家二维码
    public function getStoreCode(){ 
        $base64_image_content="data:image/jpeg;base64,".$this->getCoade($_POST['store_id']);
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){
            $type = $result[2];
            $new_file = "images/storecode/";
            if(!file_exists($new_file))
            {
            //检查是否有该文件夹，如果没有就创建，并给予最高权限
                mkdir($new_file, 0777);
            }
            $wname="{$_POST['store_id']}".".{$type}";
            //$wname="1511.jpeg";
            $new_file = $new_file.$wname;
            if(!file_exists($new_file)){
                file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_image_content)));
            }
            
        }
        echo "https://www.58zltc.com/images/storecode/".$wname;
    }
    function  getCoade($storeid){
       $img=$this->set_msg($storeid);
       $img=base64_encode($img);
       return $img;
    }
    function set_msg($storeid){
        $access_token = $this->getaccess_token();
        $data2=array(
            "scene"=>$storeid,
            "page"=>"pages/index/takeout/info",
            "width"=>400
        );
        $data2 = json_encode($data2);
        $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=".$access_token."";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,0);
        curl_setopt($ch, CURLOPT_POST,1);
        curl_setopt($ch, CURLOPT_POSTFIELDS,$data2);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }
    function getaccess_token(){
        $wid = session('wid');
        $res = M('wechat')
            ->where(array('id'=>$wid))
            ->find();
        $appid=$res['appid'];
        $secret=$res['app_secret'];
          // print_r($res);die;
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret."";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,0);
        $data = curl_exec($ch);
        curl_close($ch);
        $data = json_decode($data,true);
        return $data['access_token'];
    }
    //获取座位信息列表
    public function getTableType(){
     $wid = session('wid');
     $map = array();
     $map['wid'] = $wid;
     $map['seller_id'] = $_POST['store_id'];
     $result = M('takeout_table_type')
         ->where($map)
         ->select();
     $this->ajaxReturn($result);
   }
   //预定
    public function Reservation(){
        $wid = session('wid');
        $user_id = $this->getMemberId($_POST['openid']);
        $table_type_info = $this->getTableTypeInfo($_POST['table_type_id']);

        $data['store_id']=$_POST['store_id'];//商家id
        $data['user_id']=$user_id;//用户id
        $data['xz_date']=$_POST['xz_date'];//选择日期
        $data['yjdd_date']=$_POST['yjdd_date'];//预计到店时间
        $data['table_type_id']=$_POST['table_type_id'];//桌位类型ID
        $data['link_name']=$_POST['link_name'];//联系人
        $data['link_tel']=$_POST['link_tel'];//联系电话
        $data['jc_num']=$_POST['jc_num'];//就餐人数
        $data['remark']=$_POST['remark'];//备注
        $data['pay_money']=$_POST['money'];//付款金额
        $data['ydcode']=$_POST['ydcode'];//
        $data['order_num']=date('YmdHis',time()).rand(1111,9999);//订单号
        $data['table_type_name']=$table_type_info['name'];//桌台类型名称
        $data['zd_cost']=$table_type_info['zd_cost'];//桌台类型最低消费
        $data['state']=0;//待支付
        $data['del']=2;//未删除
        $data['wid']=$wid;//小程序id
        $data['created_time']=date('Y-m-d H:i:s');//下单时间
        $data['time2']=time();//下单时间搓
        $data['is_yue']=$_POST['is_yue'];//支付类型
        $data['is_pay'] = 0;
        $res = M('takeout_ydorder')
            ->add($data);
        $order_id=$res;
        if($res){
            $sdata = array();
            $sdata['state'] = 1;
            M('takeout_ydorder')
                ->where(array('id'=>$order_id))
                ->save($sdata);

            echo $order_id;
        }else{
            echo '预定失败';
        }
    }
    //获取用户id
    public function getMemberId($openid){
        $id = M('member')
            ->where(array('openid'=>$openid))
            ->getField('mid');
        return $id;
    }
    //获取座位类型信息
    public function getTableTypeInfo($id){
        $table_type_info = M('takeout_table_type')
            ->where(array('id'=>$id))
            ->find();
        return $table_type_info;
    }
    //预订付款
    public function reservePay(){

        $map = array();
        $map['wid'] = session('wid');
        $wechat = M("Wechat")
            ->where($map)
            ->find();

        $appid = $wechat['appid'];
        $mch_id = $wechat['mch_id'];
        $key = $wechat['partner_key'];

        $title = "预订订单付款";
        $url = "https://".$_SERVER['HTTP_HOST'].U("Notify/reserveOrder");
        // echo $url;
        $out_trade_no = $this->build_order_no();
        $data = array();
        $data['ydcode'] = $out_trade_no;
        M('takeout_ydorder')
            ->where(array('id'=>$_POST['order_id']))
            ->save($data);

        $result = $this->doWechatPay($title,$out_trade_no,$_POST['money'],$url,$_POST['openid'],$appid,$mch_id,$key);
        $this->ajaxReturn($result);
    }
    //获取预订信息
    public function getReservationInfo(){
        $result = M('takeout_ydorder')
            ->alias('y')
            ->join('tp_takeout_store s ON s.id=y.store_id')
            ->where(array('y.id'=>$_POST['id']))
            ->field('y.*,s.tel,s.logo')
            ->find();
//        $sql="select a.* ,b.name,b.tel,b.logo from " . tablename("wpdc_ydorder") . " a"  . " left join " . tablename("wpdc_store") . " b on b.id=a.store_id   WHERE a.id=:id ";
//        $list=pdo_fetch($sql,array(':id'=>$_GPC['id']));
        echo json_encode($result);
    }
    //取消预订
    public function cancelReservation(){
        $data = array();
        $data['state']=4;
        $res = M('takeout_ydorder')
            ->where(array('id'=>$_POST['id']))
            ->save($data);
        if($res){
            echo  '1';
        }else{
            echo  '2';
        }
    }
    //转换坐标
    public function transformCoordinate(){
        $op=$_POST['op'];
        $key = '37BBZ-IASRP-7VZDT-V6FJE-USUFE-OVFGR';
        $url="https://apis.map.qq.com/ws/coord/v1/translate?locations=".$op."&type=3&key=".$key;
        $ch = curl_init();

        //设置选项，包括URL
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//绕过ssl验证
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

        //执行并获取HTML文档内容
        $output = curl_exec($ch);

        //释放curl句柄
        curl_close($ch);
        $this->ajaxReturn(json_decode($output,true));
    }
    //计算店铺评分
    public function calculateScore(){
        $wid = session('wid');
        $map = array();
        $map['wid'] = $wid;
        $map['seller_id'] = $_POST['seller_id'];
        $total = M('takeout_access')
            ->where($map)
            ->sum('score');
        $count = M('takeout_access')
            ->where($map)
            ->count('id');
        if($total['total']>0 and $count['count']>0){
            echo ($total['total']/$count['count']);
        }else{
            echo '0';
        }
    }
    //获取店铺评论
    public function getStorePl(){
        $list = M('takeout_access')
            ->alias('a')
            ->join('tp_member m ON m.mid=a.user_id','LEFT')
            ->where(array('a.seller_id'=>$_POST['id']))
            ->select();
        $this->ajaxReturn($list);
    }
    //获取外卖菜品列表
    public function getDishesList()
    {

        $wid = session('wid');

        $map = array();
        $map['wid'] = $wid;
        $map['store_id'] = $_POST['id'];
        $map['is_open'] = 1;
        $type = M('takeout_type')
            ->where($map)
            ->order("order_by DESC")
            ->select();
        $lmap = array();
        $lmap['wid'] = $wid;
        $lmap['is_shelves'] = 1;
        $lmap['dishes_type'] = array('neq',$_POST['dishes_type']);
        $lmap['store_id'] = $_POST['id'];
        $list = M('takeout_dishes')
            ->where($lmap)
            ->order("sorting DESC")
            ->select();
        $data2=array();
        for($i=0;$i<count($type);$i++){
            $data=array();
            for($k=0;$k<count($list);$k++){
                if($type[$i]['id']==$list[$k]['type_id']){
                    $data[]=array(
                        'id'=>$list[$k]['id'],
                        'name'=>$list[$k]['name'],
                        'img'=>$list[$k]['img'],
                        'num'=>$list[$k]['num'],
                        'money'=>$list[$k]['money'],
                        'one'=>$list[$k]['one'],
                        'signature'=>$list[$k]['signature'],
                        'dishes_type'=>$list[$k]['dishes_type'],
                        'xs_num'=>$list[$k]['xs_num'],
                        'sit_ys_num'=>$list[$k]['sit_ys_num'],
                        'wm_money'=>$list[$k]['wm_money'],
                        'details'=>$list[$k]['details'],
                        'box_fee'=>$list[$k]['box_fee']
                    );
                }
            }
            $data2[]=array(
                'id'=>$type[$i]['id'],
                'type_name'=>$type[$i]['type_name'],
                'goods'=>$data
            );
        }
        $this->ajaxReturn($data2);
    }
    //获取外卖菜品信息
    public function getDishesInfo(){
        $res = M('takeout_dishes')
            ->where(array('id'=>$_POST['id']))
            ->find();
        $res2 = M('takeout_spec')
            ->where(array('goods_id'=>$_POST['id']))
            ->select();
        $data['dishes']=$res;
        $data['spec']=$res2;
        echo json_encode($data);
    }
    //获取菜品规格
    public function getDishesGg(){
        $res = M('takeout_spec')
            ->where(array('goods_id'=>$_POST['dishes_id']))
            ->select();
        $this->ajaxReturn($res);
    }
    //更新用户地址信息
    public function upAddress(){
        $data['user_name']=$_POST['user_name'];
        $data['user_tel']=$_POST['user_tel'];
        $data['user_address']=$_POST['user_address'];
        $res = M('member')
            ->where(array('openid'=>$_POST['openid']))
            ->save($data);
        if($res){
            echo '1';
        }else{
            echo '2';
        }
    }
    //获取用户信息
    public function getUserInfo(){
        $res = M('member')->where(array('openid'=>$_POST['openid']))->find();
        $this->ajaxReturn($res);
    }
    //查看是否为外卖新用户
    public function isNew(){
        $user_id = $this->getMemberId($_POST['openid']);
        $map = array();
        $map['user_id'] = $user_id;
        $map['type'] = 1;
        $res = M('takeout_order')
            ->where($map)
            ->find();
        if($res){
            echo  '2';//不是
        }else{
            echo  '1';//是
        }
    }
    //添加订单
    public function addOrder(){
        $wid = session('wid');
        if($_POST['type']==1){//外卖
            $data['user_id']=$_POST['user_id'];
            $data['order_num']=date('YmdHis',time()).rand(1111,9999);

            $data['state']=1;
            $data['time']=date("Y-m-d H:i:s",time());
            $data['time2']=time();
            $data['money']=$_POST['money'];
            $data['preferential']=$_POST['preferential'];
            $data['tel']=$_POST['tel'];
            $data['name']=$_POST['name'];
            $data['note']=$_POST['note'];//备注
            $data['address']=$_POST['address'];
            $data['type']=$_POST['type'];
            $data['area']=$_POST['area'];
            $data['lat']=$_POST['lat'];
            $data['lng']=$_POST['lng'];
            $data['wid']=$wid;//小程序id
            $data['freight']=$_POST['freight'];//配送费
            $data['box_fee']=$_POST['box_fee'];//餐盒费
            $data['coupons_id']=$_POST['coupons_id'];//优惠劵ID
            $data['voucher_id']=$_POST['voucher_id'];//代金劵ID
            $data['seller_id']=$_POST['seller_id'];//商家
            $data['delivery_time']=$_POST['delivery_time'];//送达时间
            $data['is_take']=$_POST['is_take'];//1.自取 2.不自取
            $data['is_yue']=$_POST['is_yue'];//1余额支付  2.微信支付  3.积分支付
            $data['form_id']=$_POST['form_id'];

            $res = M('takeout_order')
                ->add($data);
            $order_id = $res;

            $a=json_decode(html_entity_decode($_POST['sz']));
            $sz=json_decode(json_encode($a),true);
            // print_R($sz);die;

            $data3['state']=1;
            if(I('coupons_id')){
                // echo $_GPC['coupons_id'];die;
                $map = array();
                $map['coupons_id'] = $_POST['coupons_id'];
                $map['user_id'] = $_POST['user_id'];
                M('takeout_usercoupons')
                    ->where($map)
                    ->save($data3);
            }
            if(I('voucher_id')){
                $vmap = array();
                $vmap['voucher_id'] = $_POST['voucher_id'];
                $vmap['user_id'] = $_POST['user_id'];
                M('takeout_uservoucher')
                    ->where($vmap)
                    ->save($data3);
                //  echo $_GPC['voucher_id'];die;
            }
            if($res){
                for($i=0;$i<count($sz);$i++){
                    $data2['name']=$sz[$i]['name'];
                    $data2['number']=$sz[$i]['num'];
                    $data2['money']=$sz[$i]['money'];
                    $data2['img']=$sz[$i]['img'];
                    $data2['dishes_id']=$sz[$i]['dishes_id'];
                    $data2['wid']=$wid;//小程序id
                    $data2['order_id']=$order_id;
                    $res2 = M('takeout_goods')
                        ->add($data2);
                }
                echo $order_id;
            }else{
                echo '下单失败';
            }
        }elseif($_POST['type']==2){//店内
            $data['preferential']=$_POST['preferential'];
            $data['user_id']=$_POST['user_id'];
            $data['order_num']=date('YmdHis',time()).rand(1111,9999);
            $data['time']=date("Y-m-d H:i:s",time());
            $data['time2']=time();
            $data['note']=$_POST['note'];//备注
            $data['money']=$_POST['money'];
            $data['type']=$_POST['type'];
            $data['dn_state']=1;
            $data['wid']=$wid;//小程序id
            $data['table_id']=$_POST['table_id'];//桌号
            $data['coupons_id']=$_POST['coupons_id'];//优惠劵ID
            $data['voucher_id']=$_POST['voucher_id'];//代金劵ID
            $data['seller_id']=$_POST['seller_id'];//商家
            $data['is_yue']=$_POST['is_yue'];//1是  2.不是
            $data['form_id']=$_POST['form_id'];
            $res = M('takeout_order')
                ->add($data);
            $order_id=$res;
            $a=json_decode(html_entity_decode($_POST['sz']));
            $sz=json_decode(json_encode($a),true);
            $data3['state']=1;
            if(I('coupons_id')){
                M('takeout_usercoupons')
                    ->where(array('coupons_id'=>$_POST['coupons_id']))
                    ->save($data3);
            }
            if(I('voucher_id')){
                M('takeout_uservoucher')
                    ->where(array('vouchers_id'=>$_POST['voucher_id']))
                    ->save($data3);
            }
            if($res){
                M('takeout_table')
                    ->where(array('id'=>$_POST['table_id']))
                    ->save(array('status'=>2));
                for($i=0;$i<count($sz);$i++){
                    $data2['name']=$sz[$i]['name'];
                    $data2['number']=$sz[$i]['num'];
                    $data2['money']=$sz[$i]['money'];
                    $data2['img']=$sz[$i]['img'];
                    $data2['dishes_id']=$sz[$i]['dishes_id'];
                    $data2['wid']=$wid;//小程序id
                    $data2['order_id']=$order_id;
                    $res2 = M('takeout_goods')
                        ->add($data2);
                }
                echo $order_id;
            }else{
                echo '下单失败';
            }
        }
    }
    //外卖付款
    public function takeoutPay(){
        $map = array();
        $map['wid'] = session('wid');
        $wechat = M("Wechat")
                    ->where($map)
                    ->find();

        $appid = $wechat['appid'];
        $mch_id = $wechat['mch_id'];
        $key = $wechat['partner_key'];

        $title = "外卖订单付款";
        $url = "https://".$_SERVER['HTTP_HOST'].U("Notify/takeoutOrder");
        // echo $url;
        $out_trade_no = $this->build_order_no();
        $data = array();
        $data['sh_ordernum'] = $out_trade_no;
        M('takeout_order')
            ->where(array('id'=>$_POST['order_id']))
            ->save($data);

        $result = $this->doWechatPay($title,$out_trade_no,$_POST['money'],$url,$_POST['openid'],$appid,$mch_id,$key);
        //积分产生
        $pro = M('credit_setint')->where(['wid' => session('wid')])->find();
        $credit = $_POST['money'] * $pro['takeout'];
        addCredit($_POST['openid'], $credit, $_POST['order_id'], session('wid'), 6);

        $this->ajaxReturn($result);
    }
    //进行微信支付
    public function doWechatPay($title,$out_trade_no,$money,$url,$openid,$appid,$mch_id,$key){
        vendor('Weixinpay.WxPayJsApiPay');
        $tools = new \JsApiPay();
        $input = new \WxPayUnifiedOrder();
        $input->SetBody($title);
        $input->SetAttach($title);
        $input->SetOut_trade_no($out_trade_no);
        $input->SetTotal_fee(($money*100));
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        // $input->SetGoods_tag("test3");
        $input->SetNotify_url($url);   //支付回调地址，这里改成你自己的回调地址。
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($openid);
        $input->SetAppid($appid);
        $input->SetMch_id($mch_id);

        try{
            $wxorder = \WxPayApi::unifiedOrder($input, $key);
        }catch(Exception $e){
            $arr = array("err_code"=>400,"err_msg"=>$e->getMessage());
            $this->ajaxReturn($arr);
        }
        if($wxorder['return_code'] == "FAIL"){
            $arr = array("err_code"=>400,"err_msg"=>$wxorder['return_msg']);
            $this->ajaxReturn($arr);
        }
        try{
            $jsApiParameters = $tools->GetJsApiParameters($wxorder, $key);
        }catch(Exception $e){
            $arr = array("err_code"=>400,"err_msg"=>$e->getMessage());
            $this->ajaxReturn($arr);
        }

        return json_decode($jsApiParameters,true);
    }
    //获取优惠券列表
    public function getCouponsList(){
        $wid = session('wid');
        $openid = $_POST['openid'];
        $userid = $this->getMemberId($openid);
        $list = M('takeout_usercoupons')
            ->alias("a")
            ->join("tp_takeout_coupons b ON b.id=a.coupons_id","LEFT")
            ->join("tp_takeout_store c ON c.id=b.store_id","LEFT")
            ->where(array("a.user_id"=>$userid))
            ->field("a.* ,b.name,b.start_time,b.end_time,b.conditions,b.preferential,b.coupons_type,b.instruction,c.name as store_name,c.id as store_id")
            ->select();
        if($list){
            foreach($list as $k=>$v){
                $list[$k]['end_time'] = substr($v['end_time'],0,11);
            }
        }

        $res = M("takeout_coupons")
            ->alias("a")
            ->join("tp_takeout_store b ON b.id=a.store_id","LEFT")
            ->where(array('a.wid'=>$wid))
            ->field("a.* ,b.name as store_name")
            ->select();
        foreach($res as $k=>$v){
            $res[$k]['end_time'] = substr($v['end_time'],0,11);
        }
        $data['ok']=$list;
        $data['all']=$res;
        $this->ajaxReturn($data);

    }
    //获取代金券列表
    public function getVoucherList(){
        $wid = session("wid");
        $openid = $_POST['openid'];
        $userid = $this->getMemberId($openid);

        $list = M('takeout_uservoucher')
            ->alias('a')
            ->join("tp_takeout_voucher b ON b.id=a.vouchers_id","LEFT")
            ->join("tp_takeout_store c ON c.id=b.store_id","LEFT")
            ->where(array("a.user_id"=>$userid))
            ->field("a.* ,b.name,b.start_time,b.end_time,b.preferential,b.voucher_type,b.instruction,c.name as store_name ,c.id as store_id")
            ->select();

        $res = M("takeout_voucher")
            ->alias("a")
            ->join("tp_takeout_store b ON b.id=a.store_id","LEFT")
            ->where(array("a.wid"=>$wid))
            ->field("a.* ,b.name as store_name")
            ->select();

        $data['ok']=$list;
        $data['all']=$res;
        $this->ajaxReturn($data);
    }
    //领取代金券
    public function addVoucher(){
        $wid = session("wid");
        $openid = $_POST['openid'];
        $user_id = $this->getMemberId($openid);
        $data = array();
        $data['user_id'] = $user_id;
        $data['vouchers_id']=$_POST['vouchers_id'];
        $data['wid']=$wid;
        $data['state']=2;

        $map = array();
        $map['user_id'] = $user_id;
        $map['vouchers_id'] = $_POST['vouchers_id'];
        $res2 = M('takeout_uservoucher')
            ->where($map)
            ->find();

        if($res2){
            echo  '不能重复领取';
        }else{
            $res = M('takeout_uservoucher')
                ->add($data);
            if($res){
                echo '1';
            }else{
                echo '2';
            }
        }
    }
    //领取优惠券
    public function addCoupons(){
        $wid = session("wid");
        $openid = $_POST['openid'];
        $user_id = $this->getMemberId($openid);
        $data = array();
        $data['user_id'] = $user_id;
        $data['coupons_id'] = $_POST['coupons_id'];
        $data['wid'] = $wid;
        $data['state'] = 2;
        $map = array();
        $map['user_id'] = $user_id;
        $map['coupons_id'] = $_POST['coupons_id'];
        $res2 = M('takeout_usercoupons')
            ->where($map)
            ->find();

        if($res2){
            echo  '不能重复领取';
        }else{
            $res = M('takeout_usercoupons')
                ->add($data);
            if($res){
                echo '1';
            }else{
                echo '2';
            }
        }
    }
    //查看我的预约
    public function getMyReservation(){
        $user_id = $this->getMemberId($_POST['openid']);
        $map = array();
        $map['a.user_id'] = $user_id;
        $map['a.del'] = 2;
        $list = M('takeout_ydorder')
            ->alias("a")
            ->join("tp_takeout_store b ON b.id=a.store_id","LEFT")
            ->where($map)
            ->field("a.* ,b.name,b.tel,b.logo")
            ->order("a.id DESC")
            ->select();
        $this->ajaxReturn($list);
    }
    //我的订单
    public function getMyorder(){
        $user_id = $this->getMemberId($_POST['openid']);
        $map = array();
        $map['a.user_id'] = $user_id;
        $map['a.del'] = 2;
        $res = M('takeout_order')
            ->alias("a")
            ->join("tp_takeout_store b ON b.id=a.seller_id","LEFT")
            ->where($map)
            ->field("a.* ,b.logo,b.name as store_name,b.tel as store_tel")
            ->order("a.id DESC")
            ->select();
        // $res=pdo_getall('wpdc_order',array('user_id'=>$user_id), array() , '' , 'id Desc');
        $res2 = M('takeout_goods')
            ->select();
        //  $res3=pdo_get('wpdc_store',array('uniacid'=>$_W['uniacid']));
        $data2=array();
        for($i=0;$i<count($res);$i++){
            $data=array();
            for($k=0;$k<count($res2);$k++){
                if($res[$i]['id']==$res2[$k]['order_id']){
                    $data[]=array(
                        'name'=>$res2[$k]['name'],
                        'num'=>$res2[$k]['number'],
                        'img'=>$res2[$k]['img'],
                        'money'=>$res2[$k]['money'],
                        'dishes_id'=>$res2[$k]['dishes_id']
                    );
                }
            }
            $data2[]=array(
                'id'=>$res[$i]['id'],
                'order_num'=>$res[$i]['order_num'],
                'time'=>$res[$i]['time'],
                'state'=>$res[$i]['state'],
                'dn_state'=>$res[$i]['dn_state'],
                'money'=>$res[$i]['money'],
                'type'=>$res[$i]['type'],
                'tel'=>$res[$i]['store_tel'],
                'goods'=>$data,
                'img'=> $res[$i]['logo'],
                'name'=> $res[$i]['store_name'],
                'is_yue'=> $res[$i]['is_yue']
            );
        }
        $this->ajaxReturn($data2);
    }
    //订单详情
    public function getOrderInfo(){
        $res = M('takeout_order')
            ->alias("a")
            ->join("tp_takeout_table b ON b.id=a.table_id","LEFT")
            ->join("tp_takeout_table_type c ON b.type_id=c.id","LEFT")
            ->where(array("a.id"=>$_POST['id']))
            ->field("a.* ,b.name as table_name ,c.name  as  table_name_type")
            ->find();
        $res2 = M('takeout_goods')
            ->where(array('order_id'=>$_POST['id']))
            ->select();
        $res3 = M('takeout_store')
            ->where(array('id'=>$res['seller_id']))
            ->find();
        $data['order']=$res;
        $data['good']=$res2;
        $data['store']=$res3;
        $this->ajaxReturn($data);
    }
    //取消订单
    public function cancelOrder(){
        $order = M("takeout_order")
            ->where(array('id'=>$_POST['order_id']))
            ->find();
        if($order['type']==1){
            $data['state']=5;
        }elseif($order['type']==2){
            $data['dn_state']=3;
        }
        $data['cancel_time']=time();
        $res = M('takeout_order')
            ->where(array('id'=>$_POST['order_id']))
            ->save($data);
        if($res){
            $data3['state']=2;
            if($order['coupons_id']){
                $map = array();
                $map['coupons_id'] = $order['coupons_id'];
                $map['user_id'] = $order['user_id'];
                M('takeout_usercoupons')
                    ->where($map)
                    ->save($data3);
            }
            if($order['voucher_id']){
                $vmap = array();
                $vmap['vouchers_id'] = $order['vouchers_id'];
                $vmap['user_id'] = $order['user_id'];
                M('takeout_uservoucher')
                    ->where($vmap)
                    ->save($data3);
            }
            echo '1';
        }else{
            echo '2';
        }
    }
    //删除订单
    public function delOrder(){
        $res = M('takeout_order')
            ->where(array('id'=>$_POST['order_id']))
            ->save(array('del'=>1));
        if($res){
            echo '1';
        }else{
            echo '2';
        }
    }
    //申请退款
    public function refundOrder(){
        $res = M('takeout_order')
            ->where(array('id'=>$_POST['order_id']))
            ->save(array('state'=>7));
        if($res){
            echo '1';
        }else{
            echo '2';
        }
    }
    //确认收货
    public function completeOrder(){
        $data = array();
        $data['state']=4;
        $re2 = true;
        $res = M('takeout_order')
            ->where(array('id'=>$_POST['id']))
            ->save($data);
        //确认收货给店铺加钱及发放佣金
        $order = M('takeout_order')->where(array('id'=>$_POST['id']))->find();
        if($order['money']>0){
            $re2 =M('takeout_store')->where(['id'=>$order['seller_id']])->save(['takeout_money'=>$order['money']]);
            addDishesCommission(session('wid'),6,$_POST['id']);
        }

        if($res && $re2){
            echo '1';
        }else{
            echo  '2';
        }
    }
    //评论
    public function  comment(){
        $wid = session('wid');
        $user = M('member')->where(['openid'=>I('openid')])->find();
        $data['seller_id']=$_POST['seller_id'];//商家id
        $data['order_id']=$_POST['order_id'];//订单id
        $data['order_num']=$_POST['order_num'];//订单号
        $data['score']=$_POST['score'];//分数
        $data['content']=$_POST['content'];//内容
        $data['img']=$_POST['img'];//图片
        $data['cerated_time']=date("Y-m-d H:i:s",time());//创建时间
        $data['user_id']=$user['mid'];//用户id
        $data['wid']=$wid;//小程序id
        $data['status']=1;//未回复
        $res = M('takeout_access')
            ->add($data);
        $order = M('takeout_order')
            ->where(array('id'=>$_POST['order_id']))
            ->find();
        if($res){
            $total = M('takeout_access')
                ->where(array('wid'=>2,'seller_id'=>$_POST['seller_id']))
                ->sum('score');
            $count = M('takeout_access')
                ->where(array('wid'=>2,'seller_id'=>$_POST['seller_id']))
                ->count("id");
            if($total['total']>0 and $count['count']>0){
                $pf=($total/$count);
                $pf=number_format($pf,1);
            }else{
                $pf=0;
            }
            M('takeout_store')
                ->where(array('id'=>$_POST['seller_id']))
                ->save(array('score'=>$pf));
            // echo $order['type'];die;
            if($order['type']==1){
                $data2['state']=6;
            }elseif($order['type']==2){
                $data2['dn_state']=4;
            }
            //wpdc_integral
            M('takeout_order')
                ->where(array('id'=>$_POST['order_id']))
                ->save($data2);
            echo '1';
        }else{

            echo '2';

        }

    }
    //申请退款预约
    public function refundReserve(){
        $data = array();
        $data['state']=5;
        $res = M('takeout_ydorder')
            ->where(array('id'=>$_POST['id']))
            ->save($data);
        if($res){
            echo  '1';
        }else{
            echo  '2';
        }
    }
    //取消预约
    public function cancelReserve(){
        $data = array();
        $data['state']=4;
        $res = M('takeout_ydorder')
            ->where(array('id'=>$_POST['id']))
            ->save($data);
        if($res){
            echo  '1';
        }else{
            echo  '2';
        }
    }
    //删除预约
    public function delReserve(){
        $data = array();
        $data['del']=1;
        $res = M('takeout_ydorder')
            ->where(array('id'=>$_POST['id']))
            ->save($data);
        if($res){
            echo  '1';
        }else{
            echo  '2';
        }
    }
    //通过桌号查桌子名称和类型
    public function zhuohao(){
        $res = M('takeout_table')
            ->where(array('id'=>$_POST['id']))
            ->find();
        $res2 = M('takeout_table_type')
            ->where(array('id'=>$res['type_id']))
            ->find();
        $data['table_name']=$res['name'];
        $data['type_name']=$res2['name'];
        $data['status']=$res['status'];
        $this->ajaxReturn($data);
    }
    //座号
    public function getTableList(){
        $wid = session('wid');
        $map = array();
        $map['wid'] = $wid;
        $map['type_id'] = $_POST['type_id'];
        $map['status'] = 0;
        $res = M('takeout_table')
            ->where(array($map))
            ->select();
        $this->ajaxReturn($res);
    }
    //搜索店铺
    public function searchStore(){
        $wid = session('wid');
        $op=$_POST['key'];
        $where = array();
        $where['name|address'] = array('like', "%".$op."%");
        $where['is_open'] = 1;
        $where['wid'] = $wid;

        $list = M('takeout_store')
            ->where(array($where))
            ->select();
        $this->ajaxReturn($list);
    }
    public function findStoreInfo(){
        $wid = session('wid');
        $openid = $_POST['openid'];
        $info = M('takeout_store')->where(array('wid'=>$wid,'openid'=>$openid))->find();
        if(!empty($info)){
            $arr = array('status'=>1,'shop_id'=>$info['id']);
            $this->ajaxReturn($arr);
        }else{
            $arr = array('status'=>2);
            $this->ajaxReturn($arr);
        }

    }



    public function editForm(){
        $map['wid'] = session('wid');
        $wechat = M("Wechat")->where($map)->find();

        $map['id'] = $_GET['id'];
        $eq['openid'] = I("openid");
        $info = M("takeout_store")->where($eq)->find();
        $info['pics'] = explode(",", $info['pics']);

        $top_input = array('type'=>'top');

        $where['city_code'] = $wechat['city'];
        $city = M("City")->where($where)->find();
        $where1['pid'] = $city['id'];
        $site_arr2 = M("City")->where($where1)->getField("city_name",true);
        if($wechat['city'] == 0){
            $site_arr1 = array("全国");
        }else{
            $site_arr1 = array($city["city_name"]);
            if(!$site_arr2){
                $site_arr2 = array("全辖区");
            }
        }
        $site_input = array(
            'type'=>'picker2',
            'title'=>'所在区域',
            'name'=>array('county_name', 'site_name'),
            'range'=>array($site_arr1, $site_arr2),
            'value'=>array(0,0)
        );

        $cate_map['wid'] = session('wid');
        $cate_map['type'] = 'shop';
        $cate_map['pid'] = 0;

        $cates = M("Cate")->where($cate_map)->field("id as cid,title")->select();
        // dump($cates);
        foreach ($cates as $k => $v) {
            $cate_map['pid'] = $v['cid'];
            $cate_range[] = $v['title'];
            $sub_cates = M("Cate")->where($cate_map)->field("id as cid,title")->select();
            if($sub_cates){
                $cates[$k]['sub_cates'] = $sub_cates;
                foreach ($sub_cates as $key => $value) {
                    $cates[$k]['sub_range'][] = $value['title'];
                }
            }else{
                $cates[$k]['sub_cates'][] = array('cid'=>0, 'title'=>'全部');
                $cates[$k]['sub_range'][] = '全部';
            }
        }
        $area = M('takeout_area')->where(['wid'=>session('wid')])->order('num desc')->getField('area_name',true);
        $type = M('takeout_shoptype') ->where(['wid'=>session('wid')])->order('num desc')->getField('type_name',true);

        $cate_input = array(
            'type'=>'picker3',
            'title'=>'店铺分类',
            'cates'=>$cates,
            'name'=>array('cate', 'sub_cate'),
            'range'=>array($cate_range, $cates[0]['sub_range']),
            'value'=>array(0,0),
        );
        $res['add_url'] = "https://www.58zltc.com/api.php/ShopAdmin/edit";
        $res['index_url'] = "/pages/shop/shop";

        $form[] = array('type'=>'text', 'title'=>'商家名称', 'name'=>'name', 'value'=>$info['name']);

//        $form[] = $cate_input;
//        $form[] = $site_input;

        $form[] = array('type'=>'number', 'title'=>'起送费', 'name'=>'start_at', 'value'=>$info['start_at']);
        $form[] = array('type'=>'number', 'title'=>'配送费', 'name'=>'freight', 'value'=>$info['freight']);
        $form[] = array('type'=>'number', 'title'=>'配送距离(Km)', 'name'=>'distance', 'value'=>$info['distance']);
        $form[] = array('type'=>'time', 'title'=>'营业时间(上午)起', 'name'=>'time', 'value'=>$info['time']?$info['time']:'08:00');
        $form[] = array('type'=>'time', 'title'=>'营业时间(上午)终', 'name'=>'time2', 'value'=>$info['time2']?$info['time2']:'12:00');
        $form[] = array('type'=>'time', 'title'=>'营业时间(下午)起', 'name'=>'time3', 'value'=>$info['time3']?$info['time3']:'14:00');
        $form[] = array('type'=>'time', 'title'=>'营业时间(下午)终', 'name'=>'time4', 'value'=>$info['time4']?$info['time4']:'18:00');
        //$form[] = array('type'=>'time', 'title'=>'营业时间(下午)', 'name'=>'', 'value1'=>$info['start_time']?$info['start_time']:'09:00', 'name2'=>'end_time', 'value2'=>$info['end_time']?$info['end_time']:'21:00');
        $form[] = array('type'=>'top');
        $form[] = array('type'=>'pic', 'title'=>'店铺Logo', 'name'=>'logo', 'num'=>1, 'pics'=>$info['logo']?array($info['logo']):array());
        $form[] = array('type'=>'top');
        $form[] = array('type'=>'pic', 'title'=>'顶部轮播', 'name'=>'img', 'num'=>2, 'pics'=>explode(',', $info['img']));
        $form[] = array('type'=>'top');
        $form[] = array('type'=>'pic', 'title'=>'店铺环境', 'name'=>'environment', 'num'=>3, 'pics'=>explode(',', $info['environment']));
        $form[] = array('type'=>'top');
        $form[] = array('type'=>'pic', 'title'=>'店铺资质', 'name'=>'yyzz', 'num'=>4, 'pics'=>explode(',', $info['yyzz']));
        $form[] = array('type'=>'top');
        $form[] = array('type'=>'textarea', 'title'=>'详细介绍', 'name'=>'details', 'value'=>$info['details']);
        $form[] = array('type'=>'top');
        $form[] = array('type'=>'number', 'title'=>'商家电话', 'name'=>'tel', 'value'=>$info['tel']);
        $form[] = array('type'=>'text', 'title'=>'店铺地址', 'name'=>'address', 'value'=>$info['address']);
        $form[] = array('type'=>'textarea', 'title'=>'店铺公告', 'name'=>'announcement', 'value'=>$info['announcement']);
        $form[] = array('type'=>'picker1', 'title'=>'店铺区域', 'name'=>'md_area','range'=>$area, 'value'=>$info['md_area']?:0);
        $form[] = array('type'=>'picker1', 'title'=>'店铺分类', 'name'=>'md_type','range'=>$type, 'value'=>$info['md_type']?:0);
        $form[] = array('type'=>'top');
        if (!$info['login_password']) {
            $form[] = array('type'=>'number', 'title'=>'后台登录名(手机号)', 'name'=>'login_name', 'value'=>$info['login_name']);
            $form[] = array('type'=>'password', 'title'=>'后台登录密码', 'name'=>'login_password');
            $form[] = array('type'=>'password', 'title'=>'确认后台登录密码', 'name'=>'re_login_password');
            $form[] = array('type'=>'top');
        }
        // $form[] = array('type'=>'top');
        // $form[] = array('type'=>'price', 'title'=>'平台入驻费', 'price'=>$wechat['shop_fee'], 'unit'=>'年');
        $res['form'] = $form;
        // $res[''] =
        $this->ajaxReturn($res);
    }

    public function getTakeoutStoreInfo () {
        $openid = I('openid');
        $model = M('takeout_order');
        $list = M('takeout_store')->where(['openid' => $openid])->find();
        if($list){
            $arr = explode(',',$list['coordinates']);
            $list['takeout_latitude'] = $arr[0];
            $list['takeout_longitude'] = $arr[1];
        }

        $map['time'] = date("Y-m-d");
        $map['seller_id'] = $list['id'];
        $map['is_pay'] = 1;
        //今日收入
        $list['day_money'] = $model->where($map)->sum('money')?:0;
        //今日订单数
        $list['day_order'] = $model->where($map)->count()?:0;
        //7日收入
        $map['time'] = ['gt',date("Y-m-d",strtotime("-7 days"),time())];
        $list['week_money'] = $model->where($map)->sum('money')?:0;

        //7日订单数
        $list['week_order'] = $model->where($map)->count()?:0;


        $this->ajaxReturn($list);
    }

     public function saveTakeoutStore () {
         $post = $_POST;
         if ($post['login_password'] != $post['re_login_password']) {
             $this->ajaxReturn(["err_code" => 400, "err_msg" => "密码不一致！"]);
         }
         foreach ($post as $k => $v) {
             if ($v == null) {
                 $this->ajaxReturn(["err_code" => 400, "err_msg" => "请填写全部信息"]);
             }
         }
         unset($post['re_login_password']);
         $area = M('takeout_area')->where(['wid'=>session('wid')])->order('num desc')->select();
         $type = M('takeout_shoptype') ->where(['wid'=>session('wid')])->order('num desc')->select();
         $post['wid'] = session('wid');
         $post['img'] = trim($post['img'], ',');
         $post['environment'] = trim($post['environment'], ',');
         $post['yyzz'] = trim($post['yyzz'], ',');
         $post['is_yy'] =1;//预约
         $post['is_wm'] = 1;//外卖
         $post['is_dn'] = 1;//点餐
         $post['is_pd'] = 1;//优惠券
         $post['ps_mode'] = 2;//0无 1达达跑腿 2商家配送 3uu  4人人派送
         $post['md_type'] =$type[I('md_type')]['id'];
         $post['md_area'] =$area[I('md_area')]['id'];
         $post['login_password'] = md5($post['login_password']);

          //保存数据
         $list = M('takeout_store')->where(['openid' => $post['openid']])->find();
         if ($list) {
             $suc = M('takeout_store')->where(['openid' => $post['openid']])->save($post);
         } else {
             $suc = M('takeout_store')->add($post);
         }
         $suc ? $arr = array("err_code" => 0, "err_msg" => "提交成功!") : $arr = array("err_code" => 400, "err_msg" => "网络忙！");
         $this->ajaxReturn($arr);
     }

    //开关修改店铺营业状态
    public function setRest ()
    {
        $openid = I('openid');
        $data['is_rest'] = I('is_rest');
        $list = M('takeout_store')->where(['openid' => $openid])->save($data);
        $list ? $arr = array("err_code" => 0, "err_msg" => "修改成功!") : $arr = array("err_code" => 400, "err_msg" => "网络忙！");
        $this->ajaxReturn($list);
    }

    //添加点餐信息
    public function addOrdering_info(){
        $arr =[];
        $model = M('takeout_ordering_info');
        // 查询今天内未结束的，如果有相同信息，则num加1
        $data['table_id'] = I('table_id'); //餐桌
        $data['openid'] = I('openid');
        $data['store_id'] = I('store_id'); //店铺
        $data['dishes_id'] = I('dishes_id'); //菜
        $data['status'] = 0;
        $data['time'] = array('between',date('Y-m-d 00:00:00',time()).",".date('Y-m-d 23:59:59',time()));
        $re = $model->where($data)->find();

        //1点了减号 2点了加号
        switch(I('type')){
            case 1:
                $info['num'] = ($re['num'] -1>0)?($re['num'] -1):0;
                break;
            case 2:
                $info['num'] = $re['num'] + 1;
                break;
        }
        
        //有记录则修改
        $info['update_time'] = date('Y-m-d H:i:s',time());//更新时间
        if($re){
            $re2 = $model->where($data)->save($info);
            //返回数据
            $eq['o.table_id'] = I('table_id'); //餐桌
            $eq['o.store_id'] = I('store_id'); //店铺
            $eq['o.openid'] = I('openid');
            $eq['o.dishes_id'] = I('dishes_id'); //菜
            $eq['o.status'] = 0;
            $eq['o.time'] = array('between',date('Y-m-d 00:00:00',time()).",".date('Y-m-d 23:59:59',time()));
            $new = $model->alias('o')
                ->field('o.*,d.name,m.nickname')
                ->join('tp_member m on m.openid = o.openid')
                ->join('tp_takeout_dishes d on d.id = o.dishes_id')
                ->where($eq)
                ->order('id desc')
                ->find();
        }else{
            //没有记录则添加
            $data['table_id'] = I('table_id'); //餐桌
            $data['openid'] = I('openid');
            $data['store_id'] = I('store_id'); //店铺
            $data['dishes_id'] = I('dishes_id'); //菜
            $data['time'] = date('Y-m-d H:i:s',time());
            $data['update_time'] = date('Y-m-d H:i:s',time());//更新时间
            $data['num'] = 1;
            $data['status'] = 0; //0点餐中 1支付 2吃完，走人
            $re2 = $model->where($data)->add($data);
            $new = $model->alias('o')
                ->field('o.*,d.name,m.nickname')
                ->join('tp_member m on m.openid = o.openid')
                ->join('tp_takeout_dishes d on d.id = o.dishes_id')
                ->where(['o.id'=>$re2])
                ->order('id desc')
                ->find();
        }
        if($re2){
            //点加号时候提醒
            if(I('type') ==2){
                $arr['code'] = 200;
                $arr['msg']= $new['nickname'].":".$new['name']."+1";
            }

            $this->ajaxReturn($arr);
        }else{
            $this->ajaxReturn(['code'=>400]);
        }


    }
    //获取当前桌内点餐内容
    public function getCart(){
        $eq['table_id'] = I('table_id'); //餐桌
        $eq['store_id'] = I('store_id'); //店铺
        $eq['status'] = 0;
        $eq['time'] = array('between',date('Y-m-d 00:00:00',time()).",".date('Y-m-d 23:59:59',time()));
        $model = M('takeout_ordering_info');
        $re = $model->where($eq)->select();
        $arr =[];
        if($re){
            //查出商店信息
            $store = M('takeout_store')->where(['id'=>I('store_id')])->find();
            //菜品分类
            $map = array();
            $map['t.wid'] = session('wid');
            $map['t.store_id'] = I('store_id');
            $map['is_open'] = 1;
            $type = M('takeout_type')
                ->alias('t')
                ->field('t.*')
//                ->join('tp_takeout_dishes d on d.type_id = t.id')
                ->where($map)
//                ->group('type_id')
                ->order("order_by DESC")
                ->select();

            //菜列表
            $lmap = array();
            $lmap['wid'] = session('wid');
            $lmap['is_shelves'] = 1;
            $lmap['dishes_type'] = array('neq',1);
            $lmap['store_id'] = I('store_id');

            foreach($re as $k=>$v){
                $dishes = M('takeout_dishes')->where(['id'=>$v['dishes_id']])->find();


                $lmap['type_id'] = $dishes['type_id'];
                $list = M('takeout_dishes')
                    ->where($lmap)
                    //->group('type_id')
                    ->order("sorting DESC")
                    ->select();

                /*$info['all_money'] = $dishes['money'] * $v['num'];
                $info['box_fee'] = $dishes['box_fee'];//打包费
                $info['icon'] = $dishes['img'];
                $info['id'] = $dishes['id'];
                $info['index'] = array_keys(array_column($list,'id'),$dishes['id'])[0];
                $info['name'] = $dishes['name'];
                $info['num'] = $v['num'];*/

                //获取分类id
                $info['name'] = $dishes['name'];
                $info['parentindex'] =  array_keys(array_column($type,'id'),$dishes['type_id'])[0];//返回分类的key
                $info['itemIndex'] = array_keys(array_column($list,'id'),$dishes['id'])[0];
                $info['num'] = $v['num'];
                $info['types'] = 1;
                $arr[$k]=$info;
                $arr[$k]['store'] = $store;
                unset($dishes);
                unset($list);
                unset($lmap);
            }

        }

       // echo M()->getLastSql();exit;
        $this->ajaxReturn($arr);
    }
    //清空
    public function clearOrdering_info(){
        $eq['table_id'] = I('table_id'); //餐桌
        $eq['store_id'] = I('store_id'); //店铺
        $eq['time'] = array('between',date('Y-m-d 00:00:00',time()).",".date('Y-m-d 23:59:59',time()));
        $eq['status'] = 0;
        $model = M('takeout_ordering_info');
        $re = $model->where($eq)->save(['num'=>0]);
        $this->ajaxReturn($re);
    }
    //轮询请求数据
    public function getCartAjax(){
        $arr = [];
        $arr2 = [];
        $totalPrice = I('totalPrice'); //总价
        $eq['o.table_id'] = I('table_id'); //餐桌
        $eq['o.store_id'] = I('store_id'); //店铺
        $eq['o.status'] = 0;
        $eq['o.time'] = array('between',date('Y-m-d 00:00:00',time()).",".date('Y-m-d 23:59:59',time()));
        $model = M('takeout_ordering_info');

        //查询数据库给出当前菜品总价
        $price = $model->alias('o')->field('o.*,d.money')
            ->join('tp_takeout_dishes d on d.id = o.dishes_id')
            ->where($eq)
            ->sum('o.num*d.money');

        //有人点菜(totalprice为0时，页面刚加载，不返回数据)
        //if($price != $totalPrice && $totalPrice>0){
        if($price != $totalPrice){
            //查出最新的点菜人信息
            $new = $model->alias('o')
                ->field('o.*,d.name,m.nickname')
                ->join('tp_member m on m.openid = o.openid')
                ->join('tp_takeout_dishes d on d.id = o.dishes_id')
                ->where($eq)
                ->order('update_time desc,id desc')
                ->find();

            //处理新数据并返回
            $eq2['table_id'] = I('table_id'); //餐桌
            $eq2['store_id'] = I('store_id'); //店铺
            $eq2['status'] = 0;
            $eq2['time'] = array('between',date('Y-m-d 00:00:00',time()).",".date('Y-m-d 23:59:59',time()));
            $re = $model->where($eq2)->select();
            if($re){
                //查出商店信息
                $store = M('takeout_store')->where(['id'=>I('store_id')])->find();
                //菜品分类
                $map = array();
                $map['t.wid'] = session('wid');
                $map['t.store_id'] = I('store_id');
                $map['is_open'] = 1;
                $type = M('takeout_type')
                    ->alias('t')
                    ->field('t.*')
                    ->where($map)
                    ->order("order_by DESC")
                    ->select();

                //菜列表
                $lmap = array();
                $lmap['wid'] = session('wid');
                $lmap['is_shelves'] = 1;
                $lmap['dishes_type'] = array('neq',1);
                $lmap['store_id'] = I('store_id');

                foreach($re as $k=>$v){
                    $dishes = M('takeout_dishes')->where(['id'=>$v['dishes_id']])->find();
                    //查菜列表内容
                    $lmap['type_id'] = $dishes['type_id'];
                    $list = M('takeout_dishes')
                        ->where($lmap)
                        ->order("sorting DESC")
                        ->select();

                    //获取分类id
                    $info['name'] = $dishes['name'];
                    $info['parentindex'] =  array_keys(array_column($type,'id'),$dishes['type_id'])[0];//返回分类的key
                    $info['itemIndex'] = array_keys(array_column($list,'id'),$dishes['id'])[0];//当前商品在分类数组内的key
                    $info['num'] = $v['num'];
                    $info['types'] = 1;
                    $arr2[$k]=$info;
                    $arr2[$k]['store'] = $store;
                    unset($dishes);
                    unset($list);
                    unset($lmap);
                }

            }
            //返回数据
            $arr['data'] = $arr2;
            if($price >0){
                $arr['status']['code'] = 200;
                $arr['status']['msg'] = ($price > $totalPrice)?$new['nickname'].":".$new['name']."+1":$new['nickname'].":".$new['name']."-1";
            }/*else{
                $arr['status']['code'] = 200;
                $arr['status']['msg'] =$new['nickname'].'清空购物车';
            }*/
        }else{
            $arr['status']['code'] = 0;
        }
        //没人点菜的时候，前台无需更新反回空

        $this->ajaxReturn($arr);
    }
    //呼叫服务员
    public function call()
    {
        $model = M('takeout_table');
        $map['id'] = I('id');
        $info = $model->where($map)->find();
        if($info['call'] ==1){
            $this->ajaxReturn(['code'=>0,'msg'=>'请不要重复呼叫']);
        }else{
            $re =$model->where($map)->save(['call'=>1]);
            if($re){
                $this->ajaxReturn(['code'=>0,'msg'=>'呼叫成功，服务员正在赶来中']);
            }else{
                $this->ajaxReturn(['code'=>400,'msg'=>'网络忙，请稍后再试']);
            }
        }

    }


    //店铺分类挂历
    public function shoptype()
    {
        $this->display();
    }

    /*
     * 外卖店铺订单
     *
     * */
    public function getOrderList () {
        $seller_id = I('shop_id');
        $wid       = I('wid');
        $list      = [];
        //店内
        $where['a.seller_id'] = $seller_id;
        $where['a.wid']       = $wid;
        $where['a.type']      = 2;
        $dn = M('takeout_order')->alias('a')
                                    ->field('a.*, b.name as store_name, c.name as table_name, d.name as table_name_type')
                                    ->join('tp_takeout_store b ON a.seller_id = b.id')
                                    ->join('tp_takeout_table c ON a.table_id = c.id')
                                    ->join('tp_takeout_table_type d ON c.type_id = d.id')
                                    ->where($where)
                                    ->order('time desc')
                                    ->select();
        //外卖
        $wheret['a.seller_id'] = $seller_id;
        $wheret['a.wid']       = $wid;
        $wheret['a.type']      = 1;
        $to = M('takeout_order')->alias('a')
                                    ->field('a.*, b.name as store_name')
                                    ->join('tp_takeout_store b ON a.seller_id = b.id')
                                    ->where($wheret)
                                    ->order('time desc')
                                    ->select();
        //预定
        $yd              = M('takeout_ydorder')->where(['wid' => $wid])->order('created_time desc')->select();
        $list['dn']      = $dn;
        $list['yd']      = $yd;
        $list['takeout'] = $to;
        $this->ajaxReturn($list);
    }


    //商户管理中心，获取餐饮店铺商品列表
    public function getdishes()
    {
        $model = M('takeout_store');
        $eq['s.wid'] = session('wid');
        $eq['s.openid'] = I('openid');
        $list = M('takeout_dishes')->alias('d')->field('d.*')
            ->join('tp_takeout_store s on s.id = d.store_id',"LEFT")
            ->where($eq)->select();
        $this->ajaxReturn($list);
    }

    //商户管理中心，商品管理
    public function getAddForm(){
        if($_GET['id']){
            $res = $this->getEditForm();
        }else{
            $info = M('shop')->where(['openid'=>I('openid'),'status'=>1,'is_pay'=>1,'join_end_time'=>['gt', date('Y-m-d H:i:s', time())]])->order('create_time desc')->find();
            $shop = M('shop_card_yh')->where(['shop_id'=>$info['shop_id'],'status'=>1])->find();//是否开通和同城卡
            $pics = array();
            //查询菜品分类
            $type = M('takeout_type')->alias('t')->field('t.*')
                ->join('tp_takeout_store s on s.id = t.store_id')
                ->where(['openid'=>I('openid'),'t.is_open'=>1])
                ->order('order_by desc')
                ->select();
            $typename = array_column($type,'type_name');
            $store = M('takeout_store')->where(['openid'=>I('openid')])->find();

            $res['store_id'] = $store['id'];
            $res['add_url'] = "https://www.58zltc.com/api.php/TakeOut/addDeshies";
            $form[] = array('type'=>'number', 'title'=>'排序', 'name'=>'sorting');
            $form[] = array('type'=>'text', 'title'=>'菜品名称', 'name'=>'name');
            $form[] = array('type'=>'picker1', 'title'=>'菜品分类', 'name'=>'type_id','range'=>$typename, 'value'=>0);
            $form[] = array('type'=>'pic', 'title'=>'菜品图片', 'name'=>'img','num'=>1, 'pics'=>$pics);
            $form[] = array('type'=>'top');
            $form[] = array('type'=>'number', 'title'=>'库存', 'name'=>'num');
            $form[] = array('type'=>'digit', 'title'=>'店内菜品价格', 'name'=>'money');
            $form[] = array('type'=>'digit', 'title'=>'外卖菜品价格', 'name'=>'wm_money');
            $form[] = array('type'=>'number', 'title'=>'设置月销售数量', 'name'=>'sit_ys_num');
            $form[] = array('type'=>'top');
            $form[] = array('type'=>'picker1', 'title'=>'菜品选项', 'name'=>'dishes_type','range'=>['外卖','店内','店内+外卖'], 'value'=>2);
            $form[] = array('type'=>'digit', 'title'=>'餐盒费', 'name'=>'box_fee');
            $form[] = array('type'=>'checkbox', 'title'=>'招牌', 'name'=>'signature','checked'=>true, 'value'=>1);
            $form[] = array('type'=>'checkbox', 'title'=>'是否上架', 'name'=>'is_shelves','checked'=>true, 'value'=>1);
            $form[] = array('type'=>'top');
            if($shop) {
                $form[] = array('type' => 'checkbox', 'title' => '是否参与分销', 'name' => 'is_commission', 'checked'=>true, 'value' => 1);
                $form[] = array('type' => 'picker1', 'title' => '分销类型', 'name' => 'commission_type', 'range' => ['外卖', '店内', '店内+外卖'], 'value' => 2);
                $form[] = array('type' => 'digit', 'title' => '店内一级佣金比列(%)', 'name' => 'commission_one_in');
                $form[] = array('type' => 'digit', 'title' => '店内二级佣金比列(%)', 'name' => 'commission_two_in');
                $form[] = array('type' => 'digit', 'title' => '外卖一级佣金比列(%)', 'name' => 'commission_one_out');
                $form[] = array('type' => 'digit', 'title' => '外卖二级佣金比列(%)', 'name' => 'commission_two_out');
                $form[] = array('type'=>'top');
            }
            $form[] = array('type'=>'textarea', 'title'=>'商品简介', 'name'=>'details');



           /* if($shop){
                $form[] = array('type'=>'digit', 'title'=>'会员价', 'name'=>'vip_price', 'value'=>$info['vip_price']);
                //商品参与分销以及佣金
                $form[] = array('type'=>'checkbox', 'title'=>'参与分销', 'name'=>'is_commission', 'value'=>0, 'checked'=>false);
                $form[] = array('type'=>'number', 'title'=>'一级佣金比例(%)', 'name'=>'commission_one', 'value'=>$info['commission_one']);
                $form[] = array('type'=>'number', 'title'=>'二级佣金比例(%)', 'name'=>'commission_two', 'value'=>$info['commission_two']);
            }
            $form[] = array('type'=>'number', 'title'=>'库存', 'name'=>'stock');
            $form[] = array('type'=>'top');
            $form[] = array('type'=>'checkbox', 'title'=>'开启限购', 'name'=>'is_xian', 'value'=>0, 'checked'=>false);
            $form[] = array('type'=>'number', 'title'=>'每人限购件数', 'name'=>'max_num', 'value'=>$info['max_num']);
            $form[] = array('type'=>'top');
            $form[] = array('type'=>'pic', 'title'=>'商品图片', 'name'=>'pics', 'num'=>2, 'pics'=>$pics);
            $form[] = array('type'=>'top');
            $form[] = array('type'=>'textarea', 'title'=>'商品简介', 'name'=>'content');*/
            $res['form'] = $form;
        }
        $res['index_url'] = "/pages/mine/shop/goods/list2";
        $this->ajaxReturn($res);
    }
    // 获取商品编辑表单
    private function getEditForm(){
        $map['id'] = $_GET['id'];
        $info = M("takeout_dishes")->where($map)->find();
        $shop = M('shop_card_yh')->where(['shop_id'=>$info['shop_id'],'status'=>1])->find();//添加会员价
        $pics = explode(',', $info['img']);
        $res['add_url'] = "https://www.58zltc.com/api.php/TakeOut/saveDeshies/id/{$_GET['id']}";
        //查询菜品分类
        $type = M('takeout_type')->alias('t')->field('t.*')
            ->join('tp_takeout_store s on s.id = t.store_id')
            ->where(['openid'=>I('openid'),'t.is_open'=>1])
            ->order('order_by desc')
            ->select();

        $typename = array_column($type,'type_name');
        $typeids = array_column($type,'id');
        $store = M('takeout_store')->where(['openid'=>I('openid')])->find();
        $arr =['外卖','店内','店内+外卖'];
        $form[] = array('type'=>'number', 'title'=>'排序', 'name'=>'sorting','value'=>$info['sorting']);
        $form[] = array('type'=>'text', 'title'=>'菜品名称', 'name'=>'name','value'=>$info['name']);
        $form[] = array('type'=>'picker1', 'title'=>'菜品分类', 'name'=>'type_id','range'=>$typename, 'value'=>array_keys($typeids,$info['type_id']));
        $form[] = array('type'=>'pic', 'title'=>'菜品图片', 'name'=>'img','num'=>1, 'pics'=>$pics);
        $form[] = array('type'=>'top');
        $form[] = array('type'=>'number', 'title'=>'库存', 'name'=>'num', 'value'=>$info['num']);
        $form[] = array('type'=>'digit', 'title'=>'店内菜品价格', 'name'=>'money', 'value'=>$info['money']);
        $form[] = array('type'=>'digit', 'title'=>'外卖菜品价格', 'name'=>'wm_money', 'value'=>$info['wm_money']);
        $form[] = array('type'=>'number', 'title'=>'设置月销售数量', 'name'=>'sit_ys_num', 'value'=>$info['sit_ys_num']);
        $form[] = array('type'=>'top');
        $form[] = array('type'=>'picker1', 'title'=>'菜品选项', 'name'=>'dishes_type','range'=>$arr, 'value'=>$info['dishes_type']-1);
        $form[] = array('type'=>'digit', 'title'=>'餐盒费', 'name'=>'box_fee', 'value'=>$info['box_fee']);
        $form[] = array('type'=>'checkbox', 'title'=>'招牌', 'name'=>'signature','checked'=>true, 'value'=>$info['signature']);
        $form[] = array('type'=>'checkbox', 'title'=>'是否上架', 'name'=>'is_shelves','checked'=>true, 'value'=>$info['is_shelves']);
        $form[] = array('type'=>'top');
        if($shop) {
            $form[] = array('type' => 'checkbox', 'title' => '是否参与分销', 'name' => 'is_commission', 'checked'=>true, 'value' => $info['is_commission']);
            $form[] = array('type' => 'picker1', 'title' => '分销类型', 'name' => 'commission_type', 'range' => ['外卖', '店内', '店内+外卖'], 'value' =>$info['commission_type']-1);
            $form[] = array('type' => 'digit', 'title' => '店内一级佣金比列(%)', 'name' => 'commission_one_in', 'value'=>$info['commission_one_in']);
            $form[] = array('type' => 'digit', 'title' => '店内二级佣金比列(%)', 'name' => 'commission_two_in', 'value'=>$info['commission_two_in']);
            $form[] = array('type' => 'digit', 'title' => '外卖一级佣金比列(%)', 'name' => 'commission_one_out', 'value'=>$info['commission_one_out']);
            $form[] = array('type' => 'digit', 'title' => '外卖二级佣金比列(%)', 'name' => 'commission_two_out', 'value'=>$info['commission_two_out']);
            $form[] = array('type'=>'top');
        }
        $form[] = array('type'=>'textarea', 'title'=>'商品简介', 'name'=>'details', 'value'=>$info['details']);

        $res['form'] = $form;
        return $res;
    }

    //添加商品
    public function addDeshies()
    {
        foreach (I() as $key => $value) {
            if(!is_numeric($value) && empty($value)){

                $arr = array("err_code"=>400,"err_msg"=>"请填写全部信息！");
                $this->ajaxReturn($arr);
            }
        }
        //查询菜品分类
        $type = M('takeout_type')->alias('t')->field('t.*')
            ->join('tp_takeout_store s on s.id = t.store_id')
            ->where(['openid'=>I('openid'),'t.is_open'=>1])
            ->order('order_by desc')
            ->select();
        $typeids = array_column($type,'id');

        $data['storing'] = I('storing'); //排序
        $data['name'] = I('name'); //菜品名称
        $data['type_id'] = $typeids[I('type_id')]; //菜品分类
        $data['img'] = I('img'); //菜品图片
        $data['num'] = I('num'); //菜品库存
        $data['money'] = I('money'); //店内菜品价格
        $data['wm_money'] = I('wm_money'); //外卖菜品价格
        $data['sit_ys_num'] = I('sit_ys_num'); //设置月销售数量
        $data['dishes_type'] = I('dishes_type')+1; //菜品选项 菜品类型，2为店内，1为外卖, 3店内+店外
        $data['box_fee'] = I('box_fee'); //设置餐盒费
        $data['is_shelves'] = I('is_shelves')?1:0; //是否上架
        $data['details'] = I('details'); //描述
        $data['signature'] = I('signature')?1:0; //招牌
        $data['wid'] = session('wid');
        $data['store_id'] =I('store_id');
        if(I('is_commission')){
            //分销设置
            $data['is_commission'] = I('is_commission')?1:0;//是否分销
            $data['commission_type'] = I('commission_type')+1;//分销类型 1外卖  2店内   3店内+外卖
            $data['commission_one_in'] = I('commission_one_in');//店内一级佣金比列
            $data['commission_two_in'] = I('commission_two_in');//店内二级佣金比列
            $data['commission_one_out'] = I('commission_one_out');//外卖一级佣金比列
            $data['commission_two_out'] = I('commission_two_out');//外卖二级佣金比列
        }
        $re = M('takeout_dishes')->add($data);
        if($re){
            $arr = array("err_code"=>0, "err_msg"=>"发布成功！");
            $this->ajaxReturn($arr);
        }else{
            $arr = array("err_code"=>400,"err_msg"=>"网络忙，请稍后再试！");
            $this->ajaxReturn($arr);
        }
    }
    //修改商品
    public function saveDeshies()
    {
        foreach (I() as $key => $value) {
            if(!is_numeric($value) && empty($value)){

                $arr = array("err_code"=>400,"err_msg"=>"请填写全部信息！");
                $this->ajaxReturn($arr);
            }
        }
        //查询菜品分类
        $type = M('takeout_type')->alias('t')->field('t.*')
            ->join('tp_takeout_store s on s.id = t.store_id')
            ->where(['openid'=>I('openid'),'t.is_open'=>1])
            ->order('order_by desc')
            ->select();
        $typeids = array_column($type,'id');

        $data['storing'] = I('storing'); //排序
        $data['name'] = I('name'); //菜品名称
        $data['type_id'] = $typeids[I('type_id')]; //菜品分类
        $data['img'] = I('img'); //菜品图片
        $data['num'] = I('num'); //菜品库存
        $data['money'] = I('money'); //店内菜品价格
        $data['wm_money'] = I('wm_money'); //外卖菜品价格
        $data['sit_ys_num'] = I('sit_ys_num'); //设置月销售数量
        $data['dishes_type'] = I('dishes_type')+1; //菜品选项 菜品类型，2为店内，1为外卖, 3店内+店外
        $data['box_fee'] = I('box_fee'); //设置餐盒费
        $data['is_shelves'] = I('is_shelves')?1:0; //是否上架
        $data['details'] = I('details'); //描述
        $data['signature'] = I('signature')?1:0; //招牌
        $data['wid'] = session('wid');
        $data['store_id'] =I('store_id');
        if(I('is_commission')){
            //分销设置
            $data['is_commission'] = I('is_commission')?1:0;//是否分销
            $data['commission_type'] = I('commission_type')+1;//分销类型 1外卖  2店内   3店内+外卖
            $data['commission_one_in'] = I('commission_one_in');//店内一级佣金比列
            $data['commission_two_in'] = I('commission_two_in');//店内二级佣金比列
            $data['commission_one_out'] = I('commission_one_out');//外卖一级佣金比列
            $data['commission_two_out'] = I('commission_two_out');//外卖二级佣金比列
        }
        $re = M('takeout_dishes')->where(['id'=>I('id')])->save($data);
        if($re){
            $arr = array("err_code"=>0, "err_msg"=>"发布成功！");
            $this->ajaxReturn($arr);
        }else{
            $arr = array("err_code"=>400,"err_msg"=>"网络忙，请稍后再试！");
            $this->ajaxReturn($arr);
        }
    }

    //删除商品
    public function del()
    {
        $re = M('takeout_dishes')->where(['id'=>I('id')])->delete();

        if($re){
            $arr = array("err_code"=>0, "err_msg"=>"删除成功！");
            $this->ajaxReturn($arr);
        }else{
            $arr = array("err_code"=>400,"err_msg"=>"网络忙，请稍后再试！");
            $this->ajaxReturn($arr);
        }
    }

    //获取同城卡信息
    public function getCardInfo()
    {
        $shop = M('shop')->where(['openid'=>I('openid')])->find();
        $shop_id = $shop['shop_id'];
        $info = M('shop_card_yh')->where(['shop_id'=>$shop_id])->find();
        $this->ajaxReturn($info);
    }

    //添加优惠券
    public function getCouponAddForm(){
        $res['index_url'] = "/pages/mine/shop/coupon/list";

        if($_GET['id']){
            $map['id'] = $_GET['id'];
            $info = M("takeout_coupons")->where($map)->find();
            $res['add_url'] = "https://www.58zltc.com/api.php/TakeOut/addCoupon/id/{$_GET['id']}";

            $form[] = array('type'=>'text', 'title'=>'优惠券名称', 'name'=>'name',"value"=>$info['name']);
            $form[] = array('type'=>'number', 'title'=>'优惠条件金额', 'name'=>'conditions',"value"=>$info['conditions']);
            $form[] = array('type'=>'number', 'title'=>'优惠金额', 'name'=>'preferential',"value"=>$info['preferential']);
            $form[] = array('type'=>'top');
            $form[] = array('type'=>'date', 'title'=>'开始时间', 'name'=>'start_time',"value"=>$info['start_time']);
            $form[] = array('type'=>'date', 'title'=>'结束时间', 'name'=>'end_time',"value"=>$info['end_time']);
            $form[] = array('type' => 'picker1', 'title' => '适用范围', 'name' => 'coupons_type', 'range' => ['外卖', '店内', '店内+外卖'],"value"=>$info['coupons_type']-1);
            $form[] = array('type'=>'top');
            $form[] = array('type'=>'textarea', 'title'=>'使用说明', 'name'=>'instruction',"value"=>$info['instruction']);

        }else{
            $pics = array();
            $res['add_url'] = "https://www.58zltc.com/api.php/TakeOut/addCoupon";

            $form[] = array('type'=>'text', 'title'=>'优惠券名称', 'name'=>'name');
            $form[] = array('type'=>'number', 'title'=>'优惠条件金额', 'name'=>'conditions');
            $form[] = array('type'=>'number', 'title'=>'优惠金额', 'name'=>'preferential');
            $form[] = array('type'=>'top');
            $form[] = array('type'=>'date', 'title'=>'开始时间', 'name'=>'start_time',"value"=>date("Y-m-d H:i:s",time()));
            $form[] = array('type'=>'date', 'title'=>'结束时间', 'name'=>'end_time');
            $form[] = array('type' => 'picker1', 'title' => '适用范围', 'name' => 'coupons_type', 'range' => ['外卖', '店内', '店内+外卖'],'value'=>'2');
            $form[] = array('type'=>'top');
            $form[] = array('type'=>'textarea', 'title'=>'使用说明', 'name'=>'instruction');

           /* $form[] = array('type'=>'number', 'title'=>'发放数量', 'name'=>'stock');
            $form[] = array('type'=>'text', 'title'=>'一句话简介', 'name'=>'coupon_remark');
            $form[] = array('type'=>'top');
            $form[] = array('type'=>'pic', 'title'=>'优惠券图片', 'name'=>'pics', 'num'=>2, 'pics'=>$pics);*/
            $form[] = array('type'=>'top');

        }
        $res['form'] = $form;
        $this->ajaxReturn($res);
    }
    //添加/修改优惠券
    public function addCoupon(){
        foreach ($_POST as $key => $value) {
            if(!is_numeric($value) && empty($value)){
                $arr = array("err_code"=>400,"err_msg"=>"请填写全部信息！");
                $this->ajaxReturn($arr);
            }
        }
        if($_GET['id']){
            $map['id'] = $_GET['id'];
            if(M("takeout_coupons")->where($map)->save($_POST)){
                $arr = array("err_code"=>0, "err_msg"=>"修改成功！");
                $this->ajaxReturn($arr);
            }else{
                $arr = array("err_code"=>400,"err_msg"=>"没有进行任何修改哦！");
                $this->ajaxReturn($arr);
            }
        }else{
            $eq['wid'] = session('wid');
            $eq['openid'] = $_POST['openid'];
            $_POST['store_id'] = M("takeout_store")->where($eq)->getField("id");
            $_POST['wid'] = session('wid');
            if(M('takeout_coupons')->add($_POST)){
                $arr = array("err_code"=>0, "err_msg"=>"发布成功！");
                $this->ajaxReturn($arr);
            }else{
                $arr = array("err_code"=>400,"err_msg"=>"网络忙，请稍后再试！");
                $this->ajaxReturn($arr);
            }
        }

    }

    //获取优惠券列表
    public function getCouponList(){
        $map = array();
        $map['s.wid'] = session('wid');
        if($_GET['openid']){
            $map['openid'] = $_GET['openid'];
        }

        $list = M("takeout_coupons")
            ->alias('c')
            ->field('c.*')
            ->join('tp_takeout_store s on s.id = c.store_id')
            ->where($map)->select();
        /*foreach ($list as $key => $value) {
            $list[$key]['buy_percent'] = ($value['buy_num']/$value['stock'])*100;
        }*/
        $this->ajaxReturn($list);
    }

    //删除优惠券
    public function delCoupon()
    {
        $re =M("takeout_coupons")->where(['id'=>I('id')])->delete();
        if($re){
            $arr = array("err_code"=>0, "err_msg"=>"删除成功！");
            $this->ajaxReturn($arr);
        }else{
            $arr = array("err_code"=>400,"err_msg"=>"网络忙，请稍后再试！");
            $this->ajaxReturn($arr);
        }
    }

    /*
     * 外卖订单详情
     *
     * */
    public function getOrderdetails () {
        $type_name = I('type');
        $store_id = I('store_id');
        $wid = I('wid');
        $order_id = I('order_id');

        $info = [];
        //外卖/店内详情
        if ($type_name != 'yd') {
            //订单信息
            $info = M('takeout_order')->where(['id' => $order_id])->find();
            $info['yjdd_date'] = 'no';
            //订单商品
            $goods_list = M('takeout_goods')->alias('a')
                ->field('a.number, a.money, b.name, b.img')
                ->join('tp_takeout_dishes b ON a.dishes_id = b.id')
                ->where(['a.order_id' => $order_id])
                ->select();
            //合计总金额
            $money = 0;
            if ($goods_list) {
                foreach ($goods_list as $k => $v) {
                    $sMoney = $v['number'] * $v['money'];
                    $money += $sMoney;
                }
            }
        }
        //预定详情
        else {
            $yid               = I('order_id');
            $arr               = M('takeout_ydorder')->where(['id' => $yid])->find();
            $info['order_num'] = $arr['order_num'];
            $info['time']      = $arr['created_time'];
            $info['name']      = $arr['link_name'];
            $info['tel']       = $arr['link_tel'];
            $info['address']   = '';
            $info['pay_time']  = $arr['pay_time'];
            //预计到店时间
            $info['yjdd_date'] = $arr['yjdd_date'];
            $info['note']      = $arr['remark'];
            $info['type']      = 3;
            $info['yd_state']  = $arr['state'];
            $info['money']     = $arr['pay_money'];
            $info['freight']   = 0;
            $info['box_fee']   = 0;
        }
        $arrs['money'] = $money;
        $arrs['goods_list'] = $goods_list;
        $arrs['info'] = $info;
        $this->ajaxReturn($arrs);
    }
    
    /*
     * 确认外卖订单
     * 
     * */
    public function changeOrderState () {
        $id = I('order_id');
        $type = I('type');
        if ($type == 'que') {
            $order =  M('takeout_order')->where(['id' => $id])->find();
            $row = M('takeout_order')->where(['id' => $id])->save(['state' => 3]);
            if ($row) {
                //订单商品
                $goods_list = M('takeout_goods')->alias('a')
                    ->field('a.number, a.money, b.name, b.img')
                    ->join('tp_takeout_dishes b ON a.dishes_id = b.id')
                    ->where(['a.order_id' => $id])
                    ->select();
                //打印小票
                $p_info = M('takeout_printer')->where(['store_id' => session('store_id'), 'wid' => session('wid'), 'state' => 1])->select();
                foreach ($p_info as $keys => $val) {
                    if ($val['type'] == 1) {
                        //365打印机
                        $DEVICE_NO = $val['dyj_id'];
                        $key = $val['dyj_key'];
                        $content  = "";
                        $content .= "<CB>".$val['dyj_title']."</CB><BR>";
                        $content .= "名称　　　　　 单价  数量 金额";
                        $content .= "--------------------------------<BR>";
                        foreach ($goods_list as $k => $v) {
                            $content .=  $v['name']."　　 ".$v['money']." ".$v['number']."   ".$v['money'] * $v['number']."<BR>";
                        }
                        $content .= "--------------------------------<BR>";
                        $content .= "合计：".$order['money']."元<BR>";
                        $content .= "送货地点：".$order['address']."<BR>";
                        $content .= "联系电话：".$order['tel']."<BR>";
                        $content .= "订餐时间：".$order['pay_time']."<BR>";
                        //打印小票
                        $result = $this->sendSelfFormatOrderInfo($DEVICE_NO, $key, 1,$content);
                    } elseif ($val['type'] == 2) {
                        //易连云打印机
                        vendor('openapi-sdk.lib.YLYOpenApiClient');
                        $api = new \YLYOpenApiClient();

                        $content = '';                          //打印内容
                        $content .= '<FS><center>外卖订单</center></FS>';
                        $content .= str_repeat('-',32);
                        $content .= '<FS><table>';
                        $content .= '<tr><td>商品</td><td>数量</td><td>价格</td></tr>';
                        foreach ($goods_list as $k => $v) {
                            $content .= "<tr><td>". $v['name']."</td><td>X".$v['number']."</td><td>￥".$v['money']."</td></tr>";
                        }
                        $content .= '</table></FS>';
                        $content .= str_repeat('-',32)."\n";
                        $content .= "<FS>金额: {$order['money']}元</FS>";

                        $machineCode = $val['zdid'];                      //授权的终端号'4004556169'
                        $accessToken = '07d681912454445f8f60ff0262154755';                      //api访问令牌
                        $originId = $order['out_trade_no'];                         //商户自定义id
                        $timesTamp = time();                    //当前服务器时间戳(10位)
                        $api->printIndex($machineCode,$accessToken,$content,$originId,$timesTamp);
                    }
                }
                $this->ajaxReturn(['error' => 0, 'msg' => '确认成功']);
            } else {
                $this->ajaxReturn(['error' => 1, 'msg' => '网络忙']);
            }
        } elseif ($type == 'ju') {
            //拒绝订单
            $suc = M('takeout_order')->where(['id' => $id])->save(['state' => 5]);
            $suc ? $this->ajaxReturn(['error' => 0, 'msg' => '已拒绝']) : $this->ajaxReturn(['error' => 1, 'msg' => '网络忙']);
        } elseif ($type == 'yd') {
            //确定预定
            $rows = M('takeout_ydorder')->where(['id' => $id])->save(['state' => 2]);
            $rows ? $this->ajaxReturn(['error' => 0, 'msg' => '确认成功']) : $this->ajaxReturn(['error' => 1, 'msg' => '网络忙']);
        }
    }
    /*
     * 申请提现
     *
     * */
    public function save_putlog () {
        $post = $_POST;
        $store_id = $post['store_id'];
        $wid = $post['wid'];

        //是否有待处理申请
        $wi = M('withdraw')->where(['store_id' => $store_id, 'wid' => $wid, 'state_takeout' => 0])->find();
        if ($wi) {
            $this->ajaxReturn(['error' => 1, 'msg' => '已申请过提现']);
        }
        if ($post['apply_money'] < 1) {
            $this->ajaxReturn(['error' => 1, 'msg' => '金额不小于1元']);
        }
        if ($post['apply_money'] > $post['takeout_money']) {
            $this->ajaxReturn(['error' => 1, 'msg' => '超出可提现额度']);
        }
        if ($post['name'] == '') {
            $this->ajaxReturn(['error' => 1, 'msg' => '姓名不能为空']);
        }
        if ($post['apply_money'] < $post['min']) {
            $this->ajaxReturn(['error' => 1, 'msg' => '最少提现'.$post['min'].'元']);
        }
        $data                  = [];
        $data['store_id']      = $store_id;
        $data['wid']           = $wid;
        $data['apply_money']   = $post['apply_money'];
        //实际金额
        $data['real_money']    = floor($post['apply_money'] * (100 - $post['rate'])) / 100;
        //提现账号
        $data['wx']            = $post['wx'];
        $data['name']          = $post['name'];
        $data['createtime']    = date('Y-m-d H:i:s', time());
        //待提现
        $data['state_takeout'] = 0;
        $data['rate']          = $post['rate'];
        $data['is_takeout']    = 1;
        $row = M('withdraw')->add($data);
        $row ? $this->ajaxReturn(['error' => 0, 'msg' => '申请成功']) : $this->ajaxReturn(['error' => 1, 'msg' => '网络忙']);
    }
}